package com.putao.album.child;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.bean.RelationItem;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by chen on 15-5-13.
 */
public class ActivityChildSelectRelation extends BaseActivity {

    private TextView title_tv;
    private Button right_btn;
    private ListView list_view;
    private ArrayList<RelationItem> mDatalist = new ArrayList<RelationItem>();

    private ActivityChildSelectRelationAdapter mAdapter;
    private String bundleRelation;


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            default:
                break;
        }

    }


    @Override
    public int doGetContentViewId() {
        return R.layout.activity_child_select_relation;
    }

    @Override
    public void doInitSubViews(View view) {
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(R.string.child_reation_select_title);

        right_btn = (Button) findViewById(R.id.right_btn);
        right_btn.setVisibility(View.INVISIBLE);

        list_view = (ListView) findViewById(R.id.list_view);


        list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String relation = mDatalist.get(position).getName();
                PostRelation(relation);
                mActivity.finish();
            }
        });


        addOnClickListener(R.id.back_btn);
    }

    @Override
    public void doInitData() {
        if (getIntent() != null) {
            Bundle receiveBundle = getIntent().getExtras();
            if (receiveBundle != null) {
                bundleRelation = receiveBundle.getString("relation");
            }
        }

        //doGetData();
        initRelationData();

    }

    @Override
    public void onPause() {
        super.onPause();
    }


    private String getSelected() {
        String value = null;

        return value;
    }

    private void PostRelation(String relation) {
        Bundle bundle = new Bundle();
        bundle.putString("relation", relation);
        EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_FINISH_RELATION_SELECT, bundle));
    }

    private void initRelationData() {

        RelationItem item = new RelationItem();
        item.setName("妈妈");
        item.setTag(RelationItem.Tag.MATHER);
        mDatalist.add(item);

        item = new RelationItem();
        item.setName("爸爸");
        item.setTag(RelationItem.Tag.FATHER);
        mDatalist.add(item);

        item = new RelationItem();
        item.setName("外公");
        item.setTag(RelationItem.Tag.WAIGONG);
        mDatalist.add(item);

        item = new RelationItem();
        item.setName("外婆");
        item.setTag(RelationItem.Tag.WAIPO);
        mDatalist.add(item);

        item = new RelationItem();
        item.setName("爷爷");
        item.setTag(RelationItem.Tag.YEYE);
        mDatalist.add(item);

        item = new RelationItem();
        item.setName("奶奶");
        item.setTag(RelationItem.Tag.NAINAI);
        mDatalist.add(item);

        initCustomRelationView();

        mAdapter = new ActivityChildSelectRelationAdapter(mContext, mDatalist);
        list_view.setAdapter(mAdapter);

    }

    void doGetData() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("baby_id", CommonUtils.getBabyId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_BABY_RELATIONS,
                new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true,
                new HttpRequestUtil.RequestResponseListener() {
                    @Override
                    public void success(int statuscode, String response) {
                        if (!StringHelper.isEmpty(response)) {

                            if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                                doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                            } else {
                                showToast(HttpRequestUtil.getResponseErrorMsg(response));
                            }
                        }
                    }

                    @Override
                    public void failed(int statuscode, String response) {
                        Loger.d("response:::" + response);
                        showToast(response);
                    }
                });
    }


    /**
     * 解析返回的数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("list");
        if (list != null) {
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String id = o.optString("id");
                    String name = o.optString("name");
                    String tag = o.optString("tag");

                    RelationItem item = new RelationItem();
                    item.setId(id);
                    item.setName(name);
                    item.setTag(tag);
                    mDatalist.add(item);
                }
            }
            mAdapter = new ActivityChildSelectRelationAdapter(mContext, mDatalist);
            initCustomRelationView();
            list_view.setAdapter(mAdapter);
        }
    }

    private void initCustomRelationView() {
        View convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_child_select_relation_custom, null);
        list_view.addFooterView(convertView);
        ImageView icom = (ImageView) convertView.findViewById(R.id.icom);
        final TextView name = (TextView) convertView.findViewById(R.id.name);
        final Button btn = (Button) convertView.findViewById(R.id.done);

        name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                btn.setVisibility(View.VISIBLE);
            }
        });

        if (!StringHelper.isEmpty(bundleRelation)) {
            boolean isCustom = true;
            for (int i = 0; i < mDatalist.size(); i++) {
                if (bundleRelation.equals(mDatalist.get(i).getName())) {
                    isCustom = false;
                    break;
                }
            }
            if (isCustom) {
                name.setText(bundleRelation);
            }
        }

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                PostRelation(name.getText().toString());
                finish();
            }
        });

    }

}
